package com.yc.login.web;

import com.google.gson.Gson;
import com.yc.common.vo.Result;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        final Object myinfo = request.getSession().getAttribute("myinfo");
        if(myinfo == null){
            // html => 响应重定向  否则 => Result(json)
            if(request.getRequestURI().endsWith(".html")){
                // /a/b/x.html?a=1&b=2
                // requestURI = /a/b/x.html
                String requestURI = request.getRequestURI();
                String queryString = request.getQueryString();
                if(queryString!=null){
                    requestURI += "?" + queryString;
                }
                request.getSession().setAttribute("backURI", requestURI);
                response.sendRedirect("/index.html?tologin");
            } else {
                Result result = Result.failure("请先登录系统!");
                Gson gson = new Gson();
                final String j = gson.toJson(result);
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().append(j);
            }
            return false;
        } else {
            return true;
        }
    }
}
